<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-alert
      :closable="false"
      show-icon
      :title="
        !row
          ? '默认无权限，添加权限需要点击“权限”分配'
          : '添加、编辑权限需要点击“权限”分配'
      "
      type="warning"
    />
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="角色名称" prop="title">
        <el-input v-model.trim="form.title" />
      </el-form-item>
      <el-form-item label="描述" prop="describe">
        <el-input v-model.trim="form.describe" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { defineComponent, getCurrentInstance, reactive, toRefs } from 'vue'
  import { doEdit, toResetPassword } from '@/api/system_group'

  export default defineComponent({
    name: 'TableEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const { proxy } = getCurrentInstance()
      const state = reactive({
        formRef: null,
        title: null,
        list: [],
        row: null,
        form: {
          title: '',
          describe: '',
          groupId: null,
        },
        rules: {
          title: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
          describe: [
            { required: true, trigger: 'blur', message: '请选择角色' },
          ],
        },
        dialogFormVisible: false,
      })

      const showEdit = (row) => {
        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'
          // state.form = Object.assign({}, row)
          state.form.title = row.title
          state.form.describe = row.describe
          state.form.groupId = row.groupId
          state.row = row
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          title: '',
          describe: '',
          groupId: null,
        }
        state.dialogFormVisible = false
        state.row = null
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await doEdit(state.form)
            proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      const resetPassword = async () => {
        const { msg } = await toResetPassword({ groupId: state.form.groupId })
        proxy.$baseMessage(msg, 'success', 'vab-hey-message-success')
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
        resetPassword,
      }
    },
    mounted() {},
    methods: {},
  })
</script>
